package com.xin.springcloudconsumer.service.impl;


import com.google.gson.Gson;
import com.xin.springcloudconsumer.dto.Event;
import com.xin.springcloudconsumer.dto.PageResult;
import com.xin.springcloudconsumer.feigns.EventFeign;
import com.xin.springcloudconsumer.form.EventForm;
import com.xin.springcloudconsumer.service.EventService;
import com.xin.springcloudconsumer.utils.JsonUtil;
import com.xin.springcloudconsumer.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class EventServiceImpl implements EventService {
    @Autowired
    private EventFeign eventFeign;
    Gson gson = new Gson();

    /**
     * 创建事件
     *
     * @param eventForm
     * @return
     */
    public Event create(EventForm eventForm) {
        ResultVO resultVO = eventFeign.add(eventForm);
        if (resultVO.getCode() == 0) {
            String json = JsonUtil.toJson(resultVO.getData());
            Event event = gson.fromJson(json, Event.class);
            return event;
        }
        return null;
    }

    /**
     * 更新事件
     *
     * @param eventForm
     * @param id
     * @return
     */
    public Event update(EventForm eventForm, String id) {
        ResultVO resultVO = eventFeign.update(eventForm, id);
        if (resultVO.getCode() == 0) {
            String json = JsonUtil.toJson(resultVO.getData());
            Event event = gson.fromJson(json, Event.class);
            return event;
        }
        return null;
    }

    /**
     * 删除事件
     *
     * @param id
     * @return
     */
    public boolean delete(String id) {
        ResultVO resultVO = eventFeign.delete(id);
        if (resultVO.getCode() == 0) {
            return true;
        }
        return false;
    }

    /**
     * 查询某个事件
     *
     * @param id
     * @return
     */
    public Event findOne(String id) {
        ResultVO<Event> resultVO = eventFeign.findOne(id);
        if (resultVO.getCode() == 0) {
            String json = JsonUtil.toJson(resultVO.getData());
            Event event = gson.fromJson(json, Event.class);
            return event;
        }
        return null;
    }

    /**
     * 查询某个人的事件列表
     *
     * @param openId
     * @param pageable
     * @return
     */
    public PageResult findAll(String openId, Pageable pageable) {
        ResultVO<PageResult> resultVO = eventFeign.findAll(openId, pageable.getPageNumber(), pageable.getPageSize());
        String json = JsonUtil.toJson(resultVO.getData());
        PageResult<Event> pageResult = gson.fromJson(json, PageResult.class);
        return pageResult;
    }
}
